<template>
  <div>
    <el-form :inline="true" ref="infoForm" :model="formData" class="demo-form-inline head-form">
      <el-upload  v-show="false" id="quill-upload" action="/api/qiniu/upload" name="file" multiple
         list-type="picture" :show-file-list="false" :before-upload="beforeUpload" :on-error="uploadError"
        :on-success="handleExceed">
        <el-button size="small" type="primary"></el-button>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload>


      <el-form-item label="微信号" class="demo-form-inline" prop="wxtxt" :rules="[{
                    required: true, message: '微信号不能为空', trigger: 'blur'
                  }]">
        <el-input type="text" name="wxtxt" size="small" clearable v-model="formData.wxtxt" prop='wxtxt' placeholder="请输入微信号" />
      </el-form-item>
      <el-form-item class="demo-form-inline">
        <el-button @click="submitForm('infoForm')" :loading="addBtnLoading" size="small" icon="el-icon-plus" type="primary">添加微信
        </el-button>
      </el-form-item>
    </el-form>
    <div class="tableContainer">
      <el-table stripe ref="table" :data="wxList" border row-key="id" index='index' v-loading="tableLoading">
        <el-table-column show-overflow-tooltip prop="content" label="微信号" align="center">
          <template slot-scope="{row}">
            <div v-if='row.ed'>
              <el-input v-model="row.content" placeholder="请输入内容" size="small"></el-input>
            </div>
            <div v-else>
              {{row.content}}
            </div>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="coverUrl" label="二维码" align="center">
          <template slot-scope="{row}">
                <div class="codeBox" @click="upWxImg(row)">
                    <img :src="row.coverUrl||'https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png'" />
                </div>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="status" label="显示状态" align="center">
          <template slot-scope="{row}">
            {{ row.status === 1 ? '正常' : '禁用' }}
            <el-switch v-if="!isAdmin||btnFunc.some(btn=>btn=='status')" v-model="row.status" :active-value="1"
              :inactive-value="0" size="small" @change="setStatus(row)" />
          </template>
        </el-table-column>
        <el-table-column v-if="isAdmin||(btnFunc.filter(value=>value=='edit'||value=='delete').length>0)" label="操作"
          width="200" align="center" fixed="right">
          <template slot-scope="scoped">
            <el-row>
              <div v-if="isAdmin||btnFunc.some(btn=>btn=='edit')">
                <el-button type="primary" size="mini" @click="submitWxEditor(scoped)" v-if='scoped.row.ed'>
                  提交
                </el-button>
                <el-button type="danger" size="mini" @click="cancelWxEditor(scoped)" v-if='scoped.row.ed'>
                  取消
                </el-button>
                <el-tooltip v-else class="item" effect="dark" content="编辑" placement="bottom">
                  <el-button type="primary" size="mini" icon="el-icon-edit" @click="wxEditor(scoped)" />
                </el-tooltip>
              </div>

            </el-row>
          </template>
        </el-table-column>
      </el-table>



    </div>




  </div>
</template>

<script>
  import channelApi from '@/api/xcx/channel.js'
  export default {
    props: ['channelItemData'],
    data() {
      return {
        addBtnLoading: false,
        tableLoading: false,
        uillUpdateImg:false,
        curData:{

        },
        wxList: [],
        formData: {
          wxtxt: ''
        },
        isAdmin: false,
        btnFunc: [],
        channelId:""
      }

    },
    created() {
      console.log(this.wxList)
      this.getWxList(this.channelItemData);



      const {
        btnFunc,
        isAdmin
      } = this.$store.state.user;
      this.btnFunc = btnFunc
      this.isAdmin = isAdmin
    },
    mounted() {
    },
    methods: {
      upWxImg(data){
        this.curData=data;
         document.querySelector('#quill-upload input').click()
      },
      beforeUpload() { //上传图片之前开启loading
        this.tableLoading = true
      },
      uploadError() { //图片上传失败,关闭loading
        this.tableLoading = false
        this.$message.error('图片上传失败')
      },
      handleExceed(res, file, fileList) { //图片添加成功
      // alert(111)

      console.log(this.curData)
      if(res.code==200){
        this.curData.coverUrl=res.data
        channelApi.channelEditorWx(this.curData).then(res => {
          this.tableLoading = false
            if(res.code==200){
              this.$message({
                type: 'success',
                message: '操作成功！'
              });
            }
        });


      }else{
        this.tableLoading = false
        this.$message.error('图片上传失败')
      }
          console.log( this.curData)
      },
      childGetWxList(id){
          this.channelId=id;
          this.getWxList(this.channelId);
      },
      // 获取微信
      getWxList(id) {
        this.tableLoading = true
        let params = {
          pageIndex: 1,
          pageSize: 1000,
          channel: id
        }
        console.log(params)
        channelApi.channelWxList(params).then(res => {
          this.tableLoading = false;
          console.log(res);
          if (res.code == 200) {
            res.data.records.forEach((item, index) => {
              item.ed = false;
            });
            this.wxList = res.data.records;
          }
        }).catch(e => {
          this.tableLoading = false;
        })
      },
      // 添加微信
      addWx() {
        var that = this;
        let params = {
          content: this.formData.wxtxt,
          channel:this.channel||this.channelItemData,
          status: 1
        };
        channelApi.channelAddWx(params).then(res => {
          console.log(res);
          that.addBtnLoading = false;
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: '添加成功！'
            });
            this.$emit('wxAddSuccess');
            that.formData.wxtxt='';
            that.getWxList(that.channelId||that.channelItemData);
          }
        }).catch(e => {})
      },
      // 设置状态
      setStatus(data) {
        var content = ''
        if (data.status === 1) {
          content = '确定要启用吗？'
        } else {
          content = '确定要禁用吗？'
        }
        this.$confirm(content, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let params = {
            status: data.status,
            id: data.id
          }
          this.tableLoading = true;
          var that=this;
          channelApi.channelEditorWx(params).then(res => {
            if(res.code==200){
              this.$message({
                type: 'success',
                message: '操作成功！'
              })
              that.getWxList(that.channelId||that.channelItemData)
            }

          }).catch(e => {
            let wxList = JSON.parse(JSON.stringify(this.wxList))
            for (let i = 0; i < wxList.length; i++) {
              if (wxList[i].id == data.id) {
                wxList[i].status = data.status == 1 ? 0 : 1
              }
            }
            this.wxList = Object.assign([], wxList)
            this.tableLoading = false
          })
        }).catch(() => {
          let wxList = JSON.parse(JSON.stringify(this.wxList))
          for (let i = 0; i < wxList.length; i++) {
            if (wxList[i].id == data.id) {
              wxList[i].status = data.status == 1 ? 0 : 1
            }
          }
          this.wxList = Object.assign([], wxList)
          this.$message({
            type: 'info',
            message: '已取消该操作！'
          })
        });
      },
      cancelWxEditor(data){
        console.log(data.$index);
        var index_ = data.$index;
        var newData = this.wxList;
        newData.forEach(item => {
          item.ed = false;
        });
        this.wxList = newData;
      },
      wxEditor(data) {
        console.log(data.$index);
        var index_ = data.$index;
        var newData = this.wxList;
        newData.forEach(item => {
          item.ed = false;
        });
        newData[index_].ed = true;
        this.wxList = newData;
      },
      submitWxEditor(data){
        let params = {
          content: data.row.content,
          id: data.row.id
        }

        channelApi.channelEditorWx(params).then(res => {

            if(res.code==200){
              this.$message({
                type: 'success',
                message: '操作成功！'
              });
              var index_ = data.$index;
              var newData = this.wxList;
              newData[index_].ed = false;
              this.wxList = newData;
            }

        });


      },
      submitForm(formName) {
        var that = this;
        this.$refs[formName].validate((valid) => {
          console.log(valid)
          if (valid) {
            that.addBtnLoading = true;
            this.addWx();


          }
        })
      },
    }

  }
</script>

<style>
  .tableContainer {
    padding-top: 15px;
    max-height: 400px;
    overflow-y: scroll;


  }
  .codeBox{
    width:80px ;
    margin: 0 auto;
    height: 80px;
    text-align: center;
  }
  .codeBox img{
    width: 100%;
    height: 100%;
  }
</style>
